"""
在线词典的服务器端
"""
from socket import *
from threading import Thread
from dict_db import Dict


# 满足客户端需求类
class Handle(Thread):
    def __init__(self, conn, html):
        self.conn = conn
        self.html = html
        self.db = Dict()
        super().__init__()

    def close(self):
        self.db.close()
        self.conn.close()

    def run(self):
        request = self.conn.recv(1024 * 10)
        if not request:
            return
        # print(request.decode())
        lines = request.decode().split('\n')
        tmp = lines[0].split(' ')  # [GET or POST]
        print("请求内容", tmp[1])
        # 根据请求内容做处理
        if tmp[1] == '/login':
            response = self.do_login(lines[-1])
        elif tmp[1] == '/register':
            response = self.do_regist(lines[-1])
        elif tmp[1].startswith('/search'):
            # /search?word=hello
            info = tmp[1].split('=')[-1]
            print(info)
            response = self.do_queryword(info)
        else:  # html img css js
            response = self._get_response(tmp[1])
        self.conn.send(response)

    # html css js img
    def _get_response(self, info):
        if info == '/':
            info = '/login.html'
        if info[-3:] == 'css':
            response_header = b'Content-type:text/css\r\n'
        else:
            response_header = b'Content-type:text/html\r\n'
        response = b"HTTP/1.1 200 OK\r\n"
        response += response_header
        response += b"\r\n"
        try:
            with open(self.html + info, 'rb') as fr:
                data = fr.read()
            response += data
        except Exception as e:
            print(e)
            with open(self.html + '/404.html', 'rb') as fr:
                data = fr.read()
            response += data
        return response

    def do_regist(self, body):
        # user=admin&pwd1=12345&pwd2=12345
        args = body.split('&')
        user = args[0].split('=')[1]
        pwd = args[1].split('=')[1]
        if self.db.do_register(user, pwd):
            return self._get_response('/login.html')
        else:
            return self._get_response('/register.html')

    def do_queryword(self, word):
        mean = self.db.do_queryword(word)
        # 组织相应
        response = b"HTTP/1.1 200 OK\r\n"
        response += b'Content-type:text/html\r\n'
        response += b"\r\n"
        with open(self.html + "/search_res.html") as fr:
            res_page = fr.read()
        if mean:
            data = res_page % (word, mean[0])
        else:
            data = res_page % (word, "Not Found!")
        response += data.encode()
        return response

    def do_login(self, body):
        args = body.split('&')
        user = args[0].split('=')[1]
        pwd = args[1].split('=')[1]
        if self.db.do_login(user, pwd):
            return self._get_response('/search.html')
        else:
            return self._get_response('/login.html')


# 搭建网络
class Server:
    def __init__(self, host="", port=0, html=''):
        self.host = host
        self.port = port
        self.html = html  # ./static
        self.address = (host, port)
        self.sock = self.__create_sock()

    def __create_sock(self):
        sock = socket()
        sock.bind(self.address)
        return sock

    def server_start(self):
        print("Listen the port", self.port)
        self.sock.listen()
        # 等待浏览器请求
        while True:
            conn, addr = self.sock.accept()
            t = Handle(conn, self.html)
            t.start()


if __name__ == '__main__':
    s = Server(host="0.0.0.0",
               port=8800, html='../static')
    s.server_start()
